package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Banner;
import cn.wolfcode.wolf2w.query.BannerQueryObject;
import cn.wolfcode.wolf2w.redis.service.IRedisService;
import cn.wolfcode.wolf2w.repository.BannerRepository;
import cn.wolfcode.wolf2w.service.IBannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class BannerServiceImpl implements IBannerService {

    @Autowired
    private BannerRepository bannerRepository;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private MongoTemplate template;


    @Override
    public void insert(Banner banner) {
        bannerRepository.insert(banner);
    }

    @Override
    public void delete(String id) {
        bannerRepository.deleteById(id);
    }

    @Override
    public void update(Banner banner) {
        bannerRepository.save(banner);
    }

    @Override
    public Banner selectOne(String id) {
        return null;
    }

    @Override
    public List<Banner> selectAll() {
        return null;
    }

    @Override
    public Page<Banner> query(BannerQueryObject qo) {
        //查询封装类
        Query query = new Query();
        //查询数据总数
        Long count = template.count(query, Banner.class);
        //判断查询总数是否为空
        if(count==null) {
            //若为空，返回一个空集合
            return Page.empty();
        }
        //引入分页插件
        Pageable pageable=PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.DESC,"_id");
        query.with(pageable);
        List<Banner> banners = template.find(query, Banner.class);
        return new PageImpl<>(banners,pageable,count);
    }

    @Override
    public void saveOrUpdate(Banner banner) {
        if(StringUtils.hasLength(banner.getId())){
            this.update(banner);
        }else{
            //save
            this.insert(banner);
        }
    }

    @Override
    public List<Banner> queryByTypeAndState() {
        Pageable pageable=PageRequest.of(0, 5, Sort.Direction.ASC,"sequence");
        List<Banner> banners=bannerRepository.findByTypeAndState(Banner.TYPE_TRAVEL,Banner.STATE_NORMAL,pageable);
        return banners;
    }

    @Override
    public List<Banner> queryByTypeAndStateForStrategy() {
        Pageable pageable=PageRequest.of(0, 5, Sort.Direction.ASC,"sequence");
        List<Banner> banners=bannerRepository.findByTypeAndState(Banner.TYPE_STRATEGY,Banner.STATE_NORMAL,pageable);
        return banners;
    }


}
